import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { Table, Button, Tag, Message, Collapse, Alert } from 'element-react';
import _ from "underscore";
import axios from 'axios';
import 'element-theme-default';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      initDataFinish: false,
      isStart: false,
      historyResult: [],
      tableInfo: {
        groupName: "优先组",
        groupNum: 1,
        roomNum: 40,
        matchRoomNum: 40,
        columns: [
          {
            label: "序号",
            prop: "index",
            width: 130,
          },
          {
            label: "姓名",
            prop: "name",

          },
          {
            label: "身份证号",
            prop: "idcard",

          },
          {
            label: "房间号",
            prop: "roomnum"
          }
        ],
        data: []
      }
    }
  }

  componentDidMount() {
    const me = this;


    axios.get('http://localhost:8080/test/')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });


    setTimeout(function () {
      let roomInfos = [];
      let userInfos = [];
      //防止断点，要将摇号的结果每次点击开始的时候匹配完成保存在数据库
      let alreadyMatchPriorityGroupNum = 0;
      let alreadyMatchNormalGroupNum = 0;
      let leftWait = 0;
      // 3764户家庭
      for (var i = 0; i < 3764; i++) {
        let userInfo = { name: "姓名" + i, idcard: "36232419970514" + i, isSpecial: i < 72 ? "Y" : "N" }
        userInfos.push(userInfo);
      }

      // 934套房源
      for (var i = 0; i < 934; i++) {
        let roomInfo = { roomName: "安新小区", roomAddress: i + "栋10" + i }
        roomInfos.push(roomInfo);
      }


      document.addEventListener('keyup', function (e) {
        switch (e.keyCode) {
          case 32:
            if (me.state.startRandom) {
              me.handleStop();
            } else {
              me.handleStart();
            }
            break;
          case 13:
            if (me.state.startRandom) {
              me.handleStop();
            } else {
              me.handleStart();
            }
            break;
          default:
            break
        }
      });

      me.setState({
        initDataFinish: true,
        userInfos,
        roomInfos,
        alreadyMatchPriorityGroupNum,
        alreadyMatchNormalGroupNum,
        leftWait
      });
    }, 10)
  }

  handleStart() {
    const me = this;
    let startTime = new Date().getTime();
    if (me.endTime && startTime - me.endTime < 60 * 1000) {
      Message('摇号结束1分钟后，才能再次开始摇号。剩余：' + (60 - parseInt((startTime - me.endTime) / 1000)) + "s");
      return;
    }

    if (me.state.startRandom) {
      return;
    }

    let tableInfo = me.state.tableInfo;
    //之前已经摇过了（突然断电）
    let leftPriority = 72 - me.state.alreadyMatchPriorityGroupNum;
    let leftNormal = 762 - me.state.alreadyMatchNormalGroupNum;
    let leftWait = 40 - me.state.leftWait;
    let randomNum = 0, type;

    if (leftPriority > 0) {
      tableInfo.groupName = "优先组";
      tableInfo.groupNum = me.state.alreadyMatchPriorityGroupNum / 40 + 1;
      tableInfo.roomNum = leftPriority >= 40 ? 40 : leftPriority;
      tableInfo.matchRoomNum = me.state.alreadyMatchPriorityGroupNum + tableInfo.roomNum;
      type = "PRIORITY";
    } else if (leftPriority === 0 && leftNormal !== 0) {
      tableInfo.groupName = "普通组";
      tableInfo.groupNum = me.state.alreadyMatchNormalGroupNum / 40 + 1;
      tableInfo.roomNum = leftNormal >= 40 ? 40 : leftNormal;
      tableInfo.matchRoomNum = me.state.alreadyMatchNormalGroupNum + tableInfo.roomNum;
      type = "NORMAL";
    } else if (leftNormal === 0 && leftWait !== 0) {
      tableInfo.groupName = "轮候号";
      tableInfo.groupNum = 1;
      tableInfo.roomNum = 40;
      tableInfo.matchRoomNum = tableInfo.roomNum;
    } else if (leftWait === 0) {
      Message('摇号结束啦');
      return;
    }
    randomNum = tableInfo.roomNum;
    window.clearInterval(window.timer);
    window.timer = setInterval(() => {
      let tableData = me.randomGetRoom(randomNum, type);
      tableInfo.data = tableData;
      me.setState({
        isStart: true,
        tableInfo,
        startRandom: true
      });
    }, 100);
  }


  handleStop() {
    const me = this;
    if (!me.state.startRandom) {
      return;
    }
    window.clearInterval(window.timer);
    let alreadyMatchPriorityGroupNum = me.state.alreadyMatchPriorityGroupNum;
    let alreadyMatchNormalGroupNum = me.state.alreadyMatchNormalGroupNum;
    let leftWait = me.state.leftWait;

    if (me.state.tableInfo.groupName === "优先组") {
      alreadyMatchPriorityGroupNum += me.state.tableInfo.data.length;
    } else if (me.state.tableInfo.groupName === "普通组") {
      alreadyMatchNormalGroupNum += me.state.tableInfo.data.length;
    } else if (me.state.tableInfo.groupName === "轮候号") {
      leftWait += me.state.tableInfo.data.length;
    }
    let roomInfos = me.state.roomInfos;
    let userInfos = me.state.userInfos;

    for (var i = 0; i < roomInfos.length; i++) {
      var element = roomInfos[i];
      for (var j = 0; j < me.state.tableInfo.data.length; j++) {
        var data = me.state.tableInfo.data[j];
        if (data.roomnum === element.roomAddress) {
          element.isMatch = "Y";
          break;
        }
      }
    }

    for (var i = 0; i < userInfos.length; i++) {
      var element = userInfos[i];
      for (var j = 0; j < me.state.tableInfo.data.length; j++) {
        var data = me.state.tableInfo.data[j];
        if (data.idcard === element.idcard) {
          element.isMatch = "Y";
          break;
        }
      }
    }
    console.log(alreadyMatchNormalGroupNum, alreadyMatchPriorityGroupNum);
    me.setState({
      roomInfos,
      userInfos,
      alreadyMatchPriorityGroupNum,
      alreadyMatchNormalGroupNum,
      leftWait,
      startRandom: false,
      historyResult: me.state.historyResult.concat(me.state.tableInfo.data)
    });
    me.endTime = new Date().getTime();

  }

  randomGetRoom(randomNum, type) {
    const me = this;
    let roomInfos = _.filter(me.state.roomInfos, (item) => item.isMatch !== "Y");
    let userInfos = _.filter(me.state.userInfos, (item) => item.isMatch !== "Y");
    if (type === "PRIORITY") {
      userInfos = _.filter(userInfos, (item) => item.isSpecial === "Y")
    } else if (type === "NORAML") {
      userInfos = _.filter(userInfos, (item) => item.isSpecial === "N")
    }


    let roomIndexSet = new Set();
    let userIndexSet = new Set();

    while (roomIndexSet.size < randomNum) {
      roomIndexSet.add(_.random(0, roomInfos.length - 1));
    }

    while (userIndexSet.size < randomNum) {
      userIndexSet.add(_.random(0, userInfos.length - 1));
    }

    let roomIndexArr = [];
    let userIndexArr = [];


    for (let a of roomIndexSet) {
      roomIndexArr.push(a);
    }

    let userInfoArr = [];
    for (let b of userIndexSet) {
      userIndexArr.push(b);
    }

    let result = [];

    for (var i = 0; i < randomNum; i++) {
      let randomUser = userInfos[userIndexArr[i]];
      let randomRoom = roomInfos[roomIndexArr[i]];

      result.push({
        index: i + 1,
        name: randomUser.name,
        idcard: randomUser.idcard,
        roomnum: randomRoom.roomAddress
      })

    }
    return result;
  }

  handleExport() {
    const me = this;

  }



  render() {
    const me = this;
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">欢迎使用房屋摇号系统</h1>
        </header>
        <p className="App-intro">
          点击下面<code>开始</code>按钮，开始摇号
        </p>
        {me.state.initDataFinish ?
          <div>
            <div>
              {me.state.isStart ? <span>
                <span className="bigBlackFont">安新小区</span>廉租房<Tag>{me.state.tableInfo.groupName}</Tag>
                第<span className="bigRedFont">{me.state.tableInfo.groupNum}</span>组&nbsp;&nbsp;&nbsp;
                                    当前户数为<span className="bigRedFont">{me.state.tableInfo.roomNum}</span>户&nbsp;&nbsp;&nbsp;
                                    当前组已匹配户数<span className="bigRedFont">{me.state.tableInfo.matchRoomNum}</span>户
                                </span> :
                <span>当前未开始&nbsp;&nbsp;&nbsp;
              当前户数为：<span className="bigRedFont">0</span>户&nbsp;&nbsp;&nbsp;
              当前组已匹配户数<span className="bigRedFont">0</span>户</span>}
            </div>





            <div style={{ float: "left", marginLeft: "5px" }}>
              <Button type="danger" onClick={me.handleStart.bind(me)} disabled={me.state.startRandom}>开始</Button>
              <Button onClick={me.handleStop.bind(me)} disabled={!me.state.startRandom} >停止</Button>
              <Button type="primary" onClick={me.handleExport.bind(me)}>导出结果</Button>
            </div>




            <Table
              style={{ width: '100%' }}
              columns={me.state.tableInfo.columns}
              data={me.state.tableInfo.data}
              border={true}
            />


            {me.state.historyResult.length > 0 && <div style={{ textAlign: "left" }}>
              <Collapse>
                <Collapse.Item title="点击查看之前摇号结果" name="1">
                  <div>
                    {me.state.historyResult.map((item, index) => {
                      return <Alert key={item.idcard} style={{ marginBottom: "2px" }} title={(index + 1) + "：" + item.name + "  " + item.idcard + "  " + item.roomnum} type="success" closable={false} />;
                    })}

                  </div>
                </Collapse.Item>
              </Collapse>
            </div>}
          </div>
          : "初始化数据..."}

      </div>
    );
  }
}

export default App;
